package com.alien.admin.context.task.handle.impl;

import com.alien.admin.context.task.handle.DeployJobHandler;
import com.alien.admin.context.task.TaskQueue;
import com.alien.admin.modules.basic.service.JenkinsService;
import com.alien.admin.modules.deploy.domain.DeployRec;
import com.alien.admin.modules.deploy.domain.DpJenkinsInstance;
import com.alien.admin.modules.deploy.repository.DeployRecRepository;
import com.alien.admin.modules.deploy.repository.DpJenkinsInstanceRepository;
import com.alien.admin.modules.deploy.service.DeployRecService;
import com.alien.admin.utils.DeployConstant;
import com.alien.admin.utils.ValidationUtil;

import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Data
@Component
public class JenkinsJobCheckHandler implements DeployJobHandler {
    @Autowired
    private DeployRecRepository deployRecRepository;
    @Autowired
    private JenkinsService jenkinsService;
    @Autowired
    private DeployRecService deployRecService;
    @Autowired
    private DpJenkinsInstanceRepository dpJenkinsInstanceRepository;
    @Autowired
    private TaskQueue taskQueue;

    @Override
    @SneakyThrows
    public void process(DeployRec deployRec) {
        try {
            // 提取构建结果和日志内容
            Long queueId = deployRec.getBuildQueueId();
            String jobName = deployRec.getProjectName();

            // 0-未构建1-构建中2-失败3-成功
            // 获取关联的jenkins实例
            Integer jenkinsInstanceId = deployRec.getJenkinsInstanceId();
            DpJenkinsInstance jenkinsInstance = dpJenkinsInstanceRepository.findById(jenkinsInstanceId).orElseGet(DpJenkinsInstance::new);
            ValidationUtil.isNull(jenkinsInstance.getId(), "DpJenkinsInstance", "id", jenkinsInstance.getId());
            Integer result = jenkinsService.getBuildResult(jenkinsInstance, jobName, queueId);
            String logContent = jenkinsService.getBuildLog(jenkinsInstance, jobName, queueId);

            // 任务中途被取消检验
            if(taskQueue.isCancelTask(deployRec.getId())) {
                return;
            }

            deployRec.setBuildLog(logContent);
            deployRec.setDeployStatus(result);

            boolean success = DeployConstant.DEPLOY_STATUS_SUCCESS.equals(result);
            boolean failed = DeployConstant.DEPLOY_STATUS_FAILED.equals(result);

            // 部署流程状态
            if (success) {
                deployRec.setStage(DeployConstant.DEPLOY_STAGE_DEPLOY);
            }
            if (failed) {
                deployRecRepository.save(deployRec);
                return;
            }

            deployRecRepository.save(deployRec);
        } catch (Exception e) {
            log.error("获取jenkins日志！", e);
            // 获取日志失败，不代表编译任务失败
        }

        // 未结束，继续入队
        taskQueue.putTaskToQueue(deployRec.getId());
    }
}